package cn.maple.general.single;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

public class MessageConsumer {
    public static void main(String[] args) throws Exception {
        //单向消息消费
        singleMessage();
    }

    /**
     *singleMessage
     * 单向消息消费
     * @throws
     */
    public static void singleMessage() throws Exception {
        // 实例化消费者Consumer
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("Single-message-Consumer"/*消费者组名*/);

        // 设置NameServer的地址
        consumer.setNamesrvAddr("localhost:9876");

        // 订阅一个或者多个Topic，以及Tag来过滤需要消费的消息
        consumer.subscribe("SingleMessage10086", "*");

        // 注册回调实现类来处理从broker拉取回来的消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                try {
                    msgs.forEach(mess ->
                            System.out.println("消费成功:=====" + new String(mess.getBody()))
                    );
                    // 标记该消息已经被成功消费
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                } catch (Exception e) {
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }

            }
        });

        // 启动消费者实例
        consumer.start();

    }
}
